<template>
  <div class="wss-message">
    <el-input v-model="text" style="width: 300px"/>
    <el-button type="primary" @click="sendMessage(text)">发送</el-button>
    <el-card class="redata">
      <p>{{ readyState|filterReadyState }}</p>
      <template v-for="(item, index) in redataArr">
        <span>{{ item }}</span>
        <template v-if="index%1===0"><br></template>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "wssMessage",
  filters: {
    filterReadyState(val) {
      switch (val) {
        case 0:
          return 'websocket正在链接中';
        case 1:
          return 'websocket已经链接并且可以通讯';
        case 2:
          return 'websocket连接正在关闭';
        case 3:
          return 'websocket连接已关闭或者没有链接成功';
        default:
          return '未开始操作'
      }
    }
  },
  data() {
    return {
      text: '',
      redataArr: [],
      readyState: ''
    }
  },
  created() {
    this.initWebSocket();
  },
  methods: {
    sendMessage(text) {
      this.readyState = this.websock.readyState;
      const agentData = text;
      //若是ws开启状态
      if (this.websock.readyState === this.websock.OPEN) {
        this.websocketsend(agentData)
      }
      // 若是 正在开启状态，则等待100毫秒
      else if (this.websock.readyState === this.websock.CONNECTING) {
        let that = this;//保存当前对象this
        setTimeout(function () {
          that.websocketsend(agentData)
        }, 300);
      }
      // 若未开启 ，则等待200毫秒
      else {
        this.initWebSocket();
        let that = this;//保存当前对象this
        setTimeout(function () {
          that.websocketsend(agentData)
        }, 500);
      }
    },
    initWebSocket() { //初始化weosocket
      const WS_URL = 'wss://liubao.org.cn/wss';
      this.websock = new WebSocket(WS_URL);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
      this.readyState = this.websock.readyState;
    },
    websocketonmessage(e) { // 数据接收
      this.readyState = this.websock.readyState;
      this.redataArr.unshift(e.data)
    },
    websocketsend(agentData) { // 数据发送
      this.readyState = this.websock.readyState;
      this.websock.send(agentData);
    },
    websocketclose(e) {  //关闭
      this.readyState = this.websock.readyState
      console.log("connection closed (" + e.code + ")");
    }
  }
}
</script>

<style scoped>
.wss-message {
  padding: 20px;
}

.redata {
  margin-top: 20px;
}
</style>
